//
//  MCUserProfileVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/4.
//

import UIKit
import SnapKit
import Kingfisher
import SwiftyJSON
import ObjectMapper
import Toast_Swift
import QMUIKit
import PGDatePicker
import RxSwift
import RxCocoa
import ZLPhotoBrowser
import CustomPopOverView
import MMPopupView



class MCUserProfileVc: MCBaseVc {
        
    var userProfile:MCUserProfileModel!
    
    var nickNameTF:UITextField!
    
    var userSexLabel:QMUILabel!
    
    var birthLabel:QMUILabel!
    
    var headerImageView:QMUIButton!
    
    private var headerStr:String?
    
    private let dispose:DisposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        self.navigationItem.title = "个人资料"
        
      
        
        loadSubView()
    }
    
    
    func loadSubView() -> Void {
        //头像
        let headerImageBtn = QMUIButton.init()
        headerImageBtn.setImage(UIImage(named: "common_blue_image"), for: .normal)
        headerImageBtn.layer.cornerRadius = 50
        headerImageBtn.layer.masksToBounds = true
        self.headerImageView = headerImageBtn
        self.view.addSubview(headerImageBtn)
        headerImageBtn.snp.makeConstraints { make in
            make.centerX.equalTo(self.view.snp.centerX).offset(0)
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(30)
            make.height.width.equalTo(100)
        }
        headerStr = userProfile.avatar
        headerImageBtn.kf.setImage(with: URL(string: userProfile.avatar ?? ""), for: .normal)
        
        headerImageBtn.rx.tap.subscribe(onNext: { event in
            let selectPhotoView = [MMItemMake("拍摄",.normal,{event in
                let camera = ZLCustomCamera()
                camera.takeDoneBlock = { [weak self] image,videoUrl in self?.saveImage(image: image, videoUrl: videoUrl)}
                self.showDetailViewController(camera, sender: nil)
            }),MMItemMake("从图库选择",.normal,{ event in
                self.showImagePicker(false)
            })]
            let sheetView = MMSheetView.init(title: "选择", items: selectPhotoView as [Any])
            sheetView?.attachedView = self.view
            sheetView?.attachedView.mm_dimBackgroundBlurEnabled = false
            sheetView?.show()
            
        }).disposed(by: dispose)
        
        
        
        //小头像
        let smallHeaderImageView = UIImageView.init()
        smallHeaderImageView.image = UIImage(named:"mine_camea_image")
        self.view.addSubview(smallHeaderImageView)
        smallHeaderImageView.snp.makeConstraints { make in
            make.bottom.equalTo(headerImageBtn.snp.bottom).offset(0.0)
            make.right.equalTo(headerImageBtn.snp.right).offset(0.0)
            make.height.width.equalTo(30)
        }
        
        
        //view 包裹
        let nickNameView = UIView.init()
        view.addSubview(nickNameView)
        nickNameView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(16)
            make.right.equalTo(view.snp.right).offset(-16)
            make.height.equalTo(51.0)
            make.top.equalTo(headerImageBtn.snp.bottom).offset(64)
        }
        
        //昵称
        let titleNickNameLabel = QMUILabel.init()
        titleNickNameLabel.text = "昵称"
        titleNickNameLabel.textColor = UIColor.qmui_color(withHexString: "#999999")
        titleNickNameLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
        nickNameView.addSubview(titleNickNameLabel)
        titleNickNameLabel.snp.makeConstraints { make in
            make.left.equalTo(nickNameView.snp.left).offset(0)
            make.centerY.equalTo(nickNameView.snp.centerY).offset(0.0)
        }
        
        
        let nickNameTextField = QMUITextField.init()
        nickNameTextField.placeholder = "请输入昵称"
        nickNameTextField.textAlignment = .right
        nickNameTextField.font = UIFont(name: "PingFangSC-Regular", size: 15)
        nickNameTextField.textColor = UIColor.qmui_color(withHexString:"#333333")
        nickNameView.addSubview(nickNameTextField)
        nickNameTextField.snp.makeConstraints { make in
            make.right.equalTo(nickNameView.snp.right).offset(0.0)
            make.bottom.equalTo(nickNameView.snp.bottom).offset(0.0)
            make.height.equalTo(nickNameView.snp.height)
            make.left.equalTo(titleNickNameLabel.snp.right).offset(10.0)
        }
        
        nickNameTF = nickNameTextField
        
        nickNameTextField.text = userProfile.name
        
        //线
        let nickNameLineView = UIView.init()
        nickNameLineView.backgroundColor = UIColor.qmui_color(withHexString: "#F0F0F0")
        nickNameView.addSubview(nickNameLineView)
        nickNameLineView.snp.makeConstraints { make in
            make.left.equalTo(nickNameView.snp.left).offset(0.0)
            make.right.equalTo(nickNameView.snp.right).offset(0.0)
            make.bottom.equalTo(nickNameView.snp.bottom).offset(0.0)
            make.height.equalTo(1)
        }
        //-----------------------------------------------------------//
        
        //性别 view 包裹
        let sexView = UIView.init()
        sexView.backgroundColor = UIColor.qmui_color(withHexString: "F7F7F9")
        view.addSubview(sexView)
        sexView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(16)
            make.right.equalTo(view.snp.right).offset(-16)
            make.height.equalTo(51.0)
            make.top.equalTo(nickNameView.snp.bottom).offset(2)
        }
        
        //性别
        let titleSexLabel = QMUILabel.init()
        titleSexLabel.text = "性别"
        titleSexLabel.textColor = UIColor.qmui_color(withHexString: "#999999")
        titleSexLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
        sexView.addSubview(titleSexLabel)
        titleSexLabel.snp.makeConstraints { make in
            make.left.equalTo(sexView.snp.left).offset(0)
            make.centerY.equalTo(sexView.snp.centerY).offset(0.0)
            
        }
        
        
    
        
        //前进的图标
        let enterSexImageView = UIImageView.init()
        enterSexImageView.image = UIImage(named: "common_enter_image")
        sexView.addSubview(enterSexImageView)
        enterSexImageView.snp.makeConstraints { make in
            make.right.equalTo(sexView.snp.right).offset(0)
            make.centerY.equalTo(sexView.snp.centerY).offset(0.0)
            make.width.equalTo(4)
            make.height.equalTo(9)
        }
        
        
        //性别值
        let titleDisSexLabel = QMUILabel.init()
        titleDisSexLabel.text = "请选择性别"
        titleDisSexLabel.textColor = UIColor.qmui_color(withHexString: "#999999")
        titleDisSexLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
        sexView.addSubview(titleDisSexLabel)
        titleDisSexLabel.snp.makeConstraints { make in
            make.right.equalTo(enterSexImageView.snp.left).offset(-5)
            make.centerY.equalTo(sexView.snp.centerY).offset(0.0)
        }
        
        userSexLabel = titleDisSexLabel
        
        if userProfile.sex == 1 {
            titleDisSexLabel.text = "男"
            titleDisSexLabel.textColor = UIColor.qmui_color(withHexString: "#333333")
        }else {
            titleDisSexLabel.text = "女"
            titleDisSexLabel.textColor = UIColor.qmui_color(withHexString: "#333333")
        }
        
        let sexTap = UITapGestureRecognizer(target: self, action: #selector(sexSelect))
        sexView.addGestureRecognizer(sexTap)
        
                 
        //线
        let sexLineView = UIView.init()
        sexLineView.backgroundColor = UIColor.qmui_color(withHexString: "#F0F0F0")
        sexView.addSubview(sexLineView)
        sexLineView.snp.makeConstraints { make in
            make.left.equalTo(sexView.snp.left).offset(0.0)
            make.right.equalTo(sexView.snp.right).offset(0.0)
            make.bottom.equalTo(sexView.snp.bottom).offset(0.0)
            make.height.equalTo(1)
        }
        //-----------------------------------------------------------//
        //生日 view 包裹
        let birthdayView = UIView.init()
        birthdayView.backgroundColor = UIColor.qmui_color(withHexString: "F7F7F9")
        view.addSubview(birthdayView)
        birthdayView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(16)
            make.right.equalTo(view.snp.right).offset(-16)
            make.height.equalTo(51.0)
            make.top.equalTo(sexView.snp.bottom).offset(2)
        }
        
        let birthTap = UITapGestureRecognizer(target: self, action: #selector(birthSelect))
        birthdayView.addGestureRecognizer(birthTap)
        
        
        //性别
        let titleBirthdayLabel = QMUILabel.init()
        titleBirthdayLabel.text = "生日"
        titleBirthdayLabel.textColor = UIColor.qmui_color(withHexString: "#999999")
        titleBirthdayLabel.font = UIFont.systemFont(ofSize: 14)
        birthdayView.addSubview(titleBirthdayLabel)
        titleBirthdayLabel.snp.makeConstraints { make in
            make.left.equalTo(birthdayView.snp.left).offset(0)
            make.centerY.equalTo(birthdayView.snp.centerY).offset(0.0)
            
        }
        
        
        //前进的图标
        let enterBirthdayImageView = UIImageView.init()
        enterBirthdayImageView.image = UIImage(named: "common_enter_image")
        birthdayView.addSubview(enterBirthdayImageView)
        enterBirthdayImageView.snp.makeConstraints { make in
            make.right.equalTo(birthdayView.snp.right).offset(0)
            make.centerY.equalTo(birthdayView.snp.centerY).offset(0.0)
            make.width.equalTo(4)
            make.height.equalTo(9)
        }
        
        
        //性别值
        let titleDisBirthdayLabel = QMUILabel.init()
        titleDisBirthdayLabel.text = "请选择生日"
        titleDisBirthdayLabel.textColor = UIColor.qmui_color(withHexString: "#999999")
        titleDisBirthdayLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
        birthdayView.addSubview(titleDisBirthdayLabel)
        titleDisBirthdayLabel.snp.makeConstraints { make in
            make.right.equalTo(enterBirthdayImageView.snp.left).offset(-5)
            make.centerY.equalTo(birthdayView.snp.centerY).offset(0.0)
        }
        
        birthLabel = titleDisBirthdayLabel
        
        if userProfile.birthday?.isEmpty == false {
            titleDisBirthdayLabel.text = userProfile.birthday ?? ""
            titleDisBirthdayLabel.textColor = UIColor.qmui_color(withHexString: "#333333")
        }
        
        
        //线
        let birthdayLineView = UIView.init()
        birthdayLineView.backgroundColor = UIColor.qmui_color(withHexString: "#F0F0F0")
        birthdayView.addSubview(birthdayLineView)
        birthdayLineView.snp.makeConstraints { make in
            make.left.equalTo(birthdayView.snp.left).offset(0.0)
            make.right.equalTo(birthdayView.snp.right).offset(0.0)
            make.bottom.equalTo(birthdayView.snp.bottom).offset(0.0)
            make.height.equalTo(1)
        }
        
        
         
        //-----------------------------------------------------------//
        //手机号 view 包裹
        let mobileView = UIView.init()
        mobileView.backgroundColor =  UIColor.qmui_color(withHexString: "F7F7F9")
        view.addSubview(mobileView)
        mobileView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(16)
            make.right.equalTo(view.snp.right).offset(-16)
            make.height.equalTo(51.0)
            make.top.equalTo(birthdayView.snp.bottom).offset(2)
        }
        
        //性别
        let titleMobileLabel = QMUILabel.init()
        titleMobileLabel.text = "手机号"
        titleMobileLabel.textColor = UIColor.qmui_color(withHexString: "#999999")
        titleMobileLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
        mobileView.addSubview(titleMobileLabel)
        titleMobileLabel.snp.makeConstraints { make in
            make.left.equalTo(mobileView.snp.left).offset(0)
            make.centerY.equalTo(mobileView.snp.centerY).offset(0.0)
            
        }
        
        
        //前进的图标
        let enterMobileImageView = UIImageView.init()
        enterMobileImageView.image = UIImage(named: "common_enter_image")
        mobileView.addSubview(enterMobileImageView)
        enterMobileImageView.snp.makeConstraints { make in
            make.right.equalTo(mobileView.snp.right).offset(0)
            make.centerY.equalTo(mobileView.snp.centerY).offset(0.0)
            make.width.equalTo(4)
            make.height.equalTo(9)
        }
        
        
        //性别值
        let titleDisMobileLabel = QMUILabel.init()
        var strPhone = userProfile.phone ?? ""
        if(strPhone.count == 11){
            let sub2 = strPhone.dropFirst(3).dropLast(4)
            strPhone = strPhone.replacingOccurrences(of: sub2,with: "****")
        }
        titleDisMobileLabel.text = strPhone
        titleDisMobileLabel.textColor = UIColor.qmui_color(withHexString:"#333333")
        titleDisMobileLabel.font = UIFont(name: "PingFangSC-Regular", size: 15)
        mobileView.addSubview(titleDisMobileLabel)
        titleDisMobileLabel.snp.makeConstraints { make in
            make.right.equalTo(enterMobileImageView.snp.left).offset(-5)
            make.centerY.equalTo(mobileView.snp.centerY).offset(0.0)
        }
        
        
        
        //线
        let mobileLineView = UIView.init()
        mobileLineView.backgroundColor = UIColor.qmui_color(withHexString: "#F0F0F0")
        mobileView.addSubview(mobileLineView)
        mobileLineView.snp.makeConstraints { make in
            make.left.equalTo(mobileView.snp.left).offset(0.0)
            make.right.equalTo(mobileView.snp.right).offset(0.0)
            make.bottom.equalTo(mobileView.snp.bottom).offset(0.0)
            make.height.equalTo(1)
        }
        
        
        let saveBtn = QMUIButton.init()
        saveBtn.setTitle("保存", for: .normal)
        saveBtn.setTitleColor(UIColor.qmui_color(withHexString: "10151C"), for: .normal)
        saveBtn.titleLabel?.font = UIFont(name: "PingFangSC-Semibold", size: 15)
        saveBtn.backgroundColor = UIColor.qmui_color(withHexString: "#F0F0F0")
        saveBtn.layer.cornerRadius = 25.0
        saveBtn.layer.masksToBounds = true
        saveBtn.addTarget(self, action: #selector(saveInfo), for: .touchUpInside)
        view.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(16)
            make.right.equalTo(view.snp.right).offset(-16)
            make.height.equalTo(50.0)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-20.0)
        }
        
        //线
        let saveLineView = UIView.init()
        saveLineView.backgroundColor = UIColor.qmui_color(withHexString: "#E9ECF3")
        view.addSubview(saveLineView)
        saveLineView.snp.makeConstraints { make in
            make.left.equalTo(view.snp.left).offset(0.0)
            make.right.equalTo(view.snp.right).offset(0.0)
            make.bottom.equalTo(saveBtn.snp.top).offset(-30.0)
            make.height.equalTo(1)
        }
        
    }
        
    @objc func birthSelect() -> Void {
        let datePickManager = PGDatePickManager()
        datePickManager.isShadeBackground = true
        datePickManager.style = .sheet
        
        let datePicker = datePickManager.datePicker!
        datePicker.delegate = self
        datePicker.datePickerMode = .date
        self.present(datePickManager, animated: true)
    }
    
   @objc func sexSelect() -> Void {
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        let femaleAction = UIAlertAction(title: "男", style: .default) { alertAction in
            self.userSexLabel.text = "男"
        }
        
        let maleAction = UIAlertAction(title: "女", style:.default) { alertAction in
            self.userSexLabel.text = "女"
        }
        
        let alertController = UIAlertController(title: "提示", message:"", preferredStyle: .actionSheet)
        alertController.addAction(cancelAction)
        alertController.addAction(femaleAction)
        alertController.addAction(maleAction)
        
        self .present(alertController, animated: true)
        
    }
    
    @objc func saveInfo() -> Void {
        setUserProfile(avatar: self.headerStr, birthStr: birthLabel.text, name: nickNameTF.text, sex: userSexLabel.text == "男" ? 1 : 2)
    }
    
    
    func setUserProfile(avatar:String?,birthStr:String?,name:String?,sex:Int?) -> Void {
        NetWorkRequest(MineVM.setMineUserProfile(avatar: avatar, birthStr: birthStr, name: name, sex: sex)) { ResponseModel in
            if ResponseModel.code == 200 {
                self.view.makeToast("资料修改成功",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    //保存图片
    func saveImage(image:UIImage?,videoUrl:URL?) -> Void {
        
        if let image = image {
            ZLPhotoManager.saveImageToAlbum(image: image) { [weak self] suc, asset in
                if suc, let asset = asset {
                    let resultModel = ZLResultModel(asset: asset, image: image, isEdited: false, index: 0)
                    self?.uploadImage(image: resultModel.image)
                }
            }
        }
    
    }
    
    func showImagePicker(_ preview:Bool) -> Void {
        let minItemSpacing:CGFloat = 2
        let minLinespacing:CGFloat = 2
        
        ZLPhotoUIConfiguration.default().minimumLineSpacing(minItemSpacing).minimumLineSpacing(minLinespacing).columnCountBlock {Int(ceil($0 / (428.0 / 4)))}
        ZLPhotoConfiguration.default().editImageConfiguration.canRedo(true)
        ZLPhotoConfiguration.default().maxSelectCount = 1
        ZLPhotoConfiguration.default().allowSelectGif = false
        ZLPhotoConfiguration.default().allowSelectVideo = false
        ZLPhotoConfiguration.default().canSelectAsset { _ in
            true
        }
        
        let ac = ZLPhotoPreviewSheet(results: nil)
    
        ac.selectImageBlock = { [weak self] results, isOriginal in
           let resultModel = results.first
            self?.uploadImage(image: resultModel?.image)
        }
        
        ac.showPhotoLibrary(sender: self)
        
    }
    
    
    func uploadImage(image:UIImage?) -> Void {
        NetWorkRequest(MineVM.uploadImage(image: image)) { ResponseModel in
            let upLoadModel = uploadmineModel(JSONString: ResponseModel.dataString)
            if upLoadModel?.link?.isEmpty == false {
                self.headerStr = upLoadModel?.link
                self.headerImageView.kf.setImage(with: URL(string: upLoadModel?.link ?? ""), for: .normal)
            }
        
            
            
            
        } failureCallback: { ResponseModel in
            self.view.makeToast("上传失败",position: .center)
        }
    }
    
    
}

extension MCUserProfileVc:PGDatePickerDelegate {
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        self.birthLabel.text = "\(String(describing: dateComponents.year!))-\(String(describing: dateComponents.month!))-\(String(describing: dateComponents.day!))"
        self.birthLabel.textColor = UIColor.qmui_color(withHexString: "#333333")
    }
}
